package breeze.pixel.weather.service.app_widget;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.RemoteViews;

import com.qweather.sdk.view.HeConfig;

import java.util.List;

import breeze.pixel.weather.App;
import breeze.pixel.weather.R;
import breeze.pixel.weather.adapter.AppWeatherManager;
import breeze.pixel.weather.adapter.IAppWeatherHelper;
import breeze.pixel.weather.adapter.weather.DailyWeatherAdapter;
import breeze.pixel.weather.adapter.weather.WeatherNowAdapter;
import breeze.pixel.weather.apps_util.utils.AppToolUtil;
import breeze.pixel.weather.apps_util.utils.appsettings.AppSettings;
import breeze.pixel.weather.main_view.view.MainView;
import breeze.pixel.weather.service.app_widget.widgets.MAppWidget_1;
import breeze.pixel.weather.service.app_widget.widgets.MAppWidget_2;
import breeze.pixel.weather.service.app_widget.widgets.MAppWidget_3;
import breeze.pixel.weather.service.app_widget.widgets.MAppWidget_4;
import breeze.pixel.weather.service.app_widget.widgets.MAppWidget_5;
import breeze.pixel.weather.service.app_widget.widgets.MAppWidget_6;

public class WeatherUtils {

    private static final String TAG = "WeatherUtils";

    @SuppressLint("StaticFieldLeak")
    public static Context context;

    private static AppSettings sets;

    private static IAppWeatherHelper helper;

    static {
        helper = AppWeatherManager.getHelper();
    }

    static {
        System.loadLibrary("app");
        context = App.getContext();
        config();
        sets = AppSettings.getInstance(context);
    }

    private static native Object getKeyData();

    public static void config() {
        Bundle bundle = (Bundle) getKeyData();
        if (sets == null) {
            sets = AppSettings.getInstance(context);
        }
        switch (sets.getDefaultKey()) {
            case 0://第一项
                HeConfig.init(bundle.getString("name_1"), bundle.getString("key_1"));
                HeConfig.switchToDevService();
                break;
            case 1://第二项
                HeConfig.init(bundle.getString("name_2"), bundle.getString("key_2"));
                HeConfig.switchToDevService();
                break;
        }
    }

    /**
     * @return 从小部件进入app的intent
     */
    private static PendingIntent getIntentToApp() {
        //点击桌面部件进入应用程序
        Intent intent = new Intent(context, MainView.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        return PendingIntent.getActivity(context, 1001, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }

    private static WeatherNowAdapter.NowBean nowBaseBean;

    public static void updateView(WeatherNowAdapter data1) {
        if (data1 == null) {
            getData();
            return;
        }
        WeatherNowAdapter.NowBean data = data1.getNowBean();
        nowBaseBean = data;
        //点击桌面部件更新
        if (data != null) {
            String           weather_code  = data.getIcon();
            String           westher_text  = data.getText();
            String           tem           = data.getTemp();
            String           wind_dir      = data.getWindDir();
            String           cityname      = sets.getDefaultCityName();
            String           day_in_week   = AppToolUtil.getDayInWeek();
            ComponentName    componentName = new ComponentName(context, MAppWidget_1.class);
            AppWidgetManager manager       = AppWidgetManager.getInstance(context);
            RemoteViews      rv            = new RemoteViews(context.getPackageName(), R.layout.widget_launcher_1);
            /*if (new File(AppToolUtil.getAppWidgetBackgroundPic_1(context)).exists() && new File(AppToolUtil.getAppWidgetBackgroundPic_1(context)).length() > 0) {
                Bitmap bitmap = AppToolUtil.roundedBitmap(sets.getBrightness(), BitmapFactory.decodeFile(AppToolUtil.getAppWidgetBackgroundPic_1(context)), 30f);
                rv.setImageViewBitmap(R.id.wid_get_1_layout, bitmap);
            } else {
                rv.setImageViewResource(R.id.wid_get_1_layout, R.drawable.cardview_tendp_white);
            }*/
//            rv.setInt(R.id.wid_get_1_layout, "setImageAlpha", sets.getAppWidgetAlpha());
//            rv.setTextColor(R.id.widget_clock, textColor);
//            rv.setTextColor(R.id.weather_tem, textColor);
//            rv.setTextColor(R.id.widget_weather_text, textColor);
//            rv.setTextColor(R.id.widget_location, textColor);
//            rv.setTextColor(R.id.widget_windspeed, textColor);
//            rv.setTextColor(R.id.widget_date, textColor);
//            rv.setTextColor(R.id.widget_week, textColor);
            rv.setImageViewBitmap(R.id.widget_icon, AppToolUtil.getweatherIcon(context, weather_code));
            rv.setTextViewText(R.id.weather_tem, tem);
            rv.setTextViewText(R.id.widget_weather_text, westher_text);
            rv.setTextViewText(R.id.widget_location, cityname);
            rv.setTextViewText(R.id.widget_windspeed, wind_dir);
            rv.setTextViewText(R.id.widget_date, AppToolUtil.getSimpleDate("MM月dd日"));
            rv.setTextViewText(R.id.widget_week, day_in_week);
            rv.setOnClickPendingIntent(R.id.wid_get_1_layout, getIntentToApp());
            manager.updateAppWidget(componentName, rv);

            //桌面部件2
            RemoteViews remoteViews2 = new RemoteViews(context.getPackageName(), R.layout.widget_launcher_2);
//            remoteViews2.setTextColor(R.id.widget2_tem, textColor);
//            remoteViews2.setTextColor(R.id.widget2_data, textColor);
//            remoteViews2.setTextColor(R.id.widget2_date, textColor);
//            remoteViews2.setTextColor(R.id.widget2_cityname, textColor);
            ComponentName componentName2 = new ComponentName(context, MAppWidget_2.class);
            remoteViews2.setOnClickPendingIntent(R.id.wid_get_2_layout, getIntentToApp());
            remoteViews2.setTextViewText(R.id.widget2_tem, data.getTemp() + "℃");
            remoteViews2.setTextViewText(R.id.widget2_data, data.getText() + "," + data.getWindDir());
            remoteViews2.setTextViewText(R.id.widget2_date, AppToolUtil.getSimpleDate("yyyy-MM-dd"));
            remoteViews2.setTextViewText(R.id.widget2_cityname, sets.getDefaultCityName());
            remoteViews2.setImageViewBitmap(R.id.widget2_icon, AppToolUtil.getweatherIcon(context, data.getIcon()));
            manager.updateAppWidget(componentName2, remoteViews2);

            int textColor = sets.getAppwidgetTextColor();
            //桌面部件3
            RemoteViews   remoteViews3   = new RemoteViews(context.getPackageName(), R.layout.widget_launcher_3);
            ComponentName componentName3 = new ComponentName(context, MAppWidget_3.class);
            remoteViews3.setOnClickPendingIntent(R.id.wid_get_3_layout, getIntentToApp());
            remoteViews3.setTextViewText(R.id.wid3_time, AppToolUtil.getSimpleDate("MM月dd日") + " " + AppToolUtil.getDayInWeek());
            remoteViews3.setTextColor(R.id.wid3_time, textColor);
            remoteViews3.setTextViewText(R.id.wid3_weather_text, data.getTemp() + "℃");
            remoteViews3.setTextColor(R.id.wid3_weather_text, textColor);
            remoteViews3.setImageViewBitmap(R.id.wid3_icon, AppToolUtil.getweatherIcon(context, data.getIcon()));
            manager.updateAppWidget(componentName3, remoteViews3);

            //桌面部件4
            RemoteViews   remoteViews4   = new RemoteViews(context.getPackageName(), R.layout.widget_launcher_4);
            ComponentName componentName4 = new ComponentName(context, MAppWidget_4.class);
            remoteViews4.setOnClickPendingIntent(R.id.wid_get_4_layout, getIntentToApp());
            remoteViews4.setTextViewText(R.id.wid4_data, data.getText() + " " + data.getTemp());
            remoteViews4.setTextColor(R.id.wid4_data, sets.getAppwidgetTextColor());
            remoteViews4.setTextViewText(R.id.wid4_date, AppToolUtil.getSimpleDate("MM月dd日"));
            remoteViews4.setTextColor(R.id.wid4_date, sets.getAppwidgetTextColor());
            remoteViews4.setTextViewText(R.id.wid4_week, AppToolUtil.getDayInWeek());
            remoteViews4.setTextColor(R.id.wid4_week, sets.getAppwidgetTextColor());
            remoteViews4.setTextColor(R.id.widget4_clock, sets.getAppwidgetTextColor());
            manager.updateAppWidget(componentName4, remoteViews4);
        }
    }

    private static DailyWeatherAdapter dailyBean7D;

    public static void update7DWeather(DailyWeatherAdapter weatherDailyBean) {
        dailyBean7D = weatherDailyBean;
        RemoteViews   remoteViews   = new RemoteViews(context.getPackageName(), R.layout.widget_launcher_6);
        ComponentName componentName = new ComponentName(context, MAppWidget_6.class);
        //点击进入app
        remoteViews.setOnClickPendingIntent(R.id.widget6_baseView, getIntentToApp());
        AppWidgetManager                    appWidgetManager = AppWidgetManager.getInstance(context);
        List<DailyWeatherAdapter.DailyBean> daily            = weatherDailyBean.getDaily();
        //设置参数-1
        Log.i(TAG, "update7DWeather: " + daily.size());
        if (daily.size() > 0) {
            DailyWeatherAdapter.DailyBean dailyBean = daily.get(0);
            remoteViews.setTextViewText(R.id.widget6_time1, AppToolUtil.getDayInWeekOfDate(dailyBean.getFxDate()));
            remoteViews.setTextViewText(R.id.widget6_temperature_1, getTemperature(dailyBean));
            remoteViews.setImageViewBitmap(R.id.widget6_icon_1, AppToolUtil.getweatherIcon(context, dailyBean.getIconDay()));
        }
        //设置参数-2
        if (daily.size() > 1) {
            DailyWeatherAdapter.DailyBean dailyBean2 = daily.get(1);
            remoteViews.setTextViewText(R.id.widget6_time2, AppToolUtil.getDayInWeekOfDate(dailyBean2.getFxDate()));
            remoteViews.setTextViewText(R.id.widget6_temperature_2, getTemperature(dailyBean2));
            remoteViews.setImageViewBitmap(R.id.widget6_icon_2, AppToolUtil.getweatherIcon(context, dailyBean2.getIconDay()));
        }
        //设置参数-3
        if (daily.size() > 2) {
            DailyWeatherAdapter.DailyBean dailyBean3 = daily.get(2);
            remoteViews.setTextViewText(R.id.widget6_time3, AppToolUtil.getDayInWeekOfDate(dailyBean3.getFxDate()));
            remoteViews.setTextViewText(R.id.widget6_temperature_3, getTemperature(dailyBean3));
            remoteViews.setImageViewBitmap(R.id.widget6_icon_3, AppToolUtil.getweatherIcon(context, dailyBean3.getIconDay()));
        }
        //设置参数-4
        if (daily.size() > 3) {
            DailyWeatherAdapter.DailyBean dailyBean4 = daily.get(3);
            remoteViews.setTextViewText(R.id.widget6_time4, AppToolUtil.getDayInWeekOfDate(dailyBean4.getFxDate()));
            remoteViews.setTextViewText(R.id.widget6_temperature_4, getTemperature(dailyBean4));
            remoteViews.setImageViewBitmap(R.id.widget6_icon_4, AppToolUtil.getweatherIcon(context, dailyBean4.getIconDay()));
        }
        //设置参数-5
        if (daily.size() > 4) {
            DailyWeatherAdapter.DailyBean dailyBean5 = daily.get(4);
            remoteViews.setTextViewText(R.id.widget6_time5, AppToolUtil.getDayInWeekOfDate(dailyBean5.getFxDate()));
            remoteViews.setTextViewText(R.id.widget6_temperature_5, getTemperature(dailyBean5));
            remoteViews.setImageViewBitmap(R.id.widget6_icon_5, AppToolUtil.getweatherIcon(context, dailyBean5.getIconDay()));
        }
        //设置参数-6
        if (daily.size() > 5) {
            DailyWeatherAdapter.DailyBean dailyBean6 = daily.get(5);
            remoteViews.setTextViewText(R.id.widget6_time6, AppToolUtil.getDayInWeekOfDate(dailyBean6.getFxDate()));
            remoteViews.setTextViewText(R.id.widget6_temperature_6, getTemperature(dailyBean6));
            remoteViews.setImageViewBitmap(R.id.widget6_icon_6, AppToolUtil.getweatherIcon(context, dailyBean6.getIconDay()));
        }
        //设置参数-当前
        if (nowBaseBean != null) {
            remoteViews.setImageViewBitmap(R.id.widget6_icon_current, AppToolUtil.getweatherIcon(context, nowBaseBean.getIcon()));
            remoteViews.setTextViewText(R.id.widget6_info, sets.getDefaultCityName() + " " + nowBaseBean.getText() + " " + nowBaseBean.getTemp() + "℃");
            remoteViews.setTextColor(R.id.widget6_info, sets.getAppwidgetTextColor());
            remoteViews.setTextColor(R.id.widget6_clock, sets.getAppwidgetTextColor());
        }
        appWidgetManager.updateAppWidget(componentName, remoteViews);
    }

    private static String getTemperature(DailyWeatherAdapter.DailyBean dailyBean) {
        return dailyBean.getTempMin() + "~" + dailyBean.getTempMax() + "℃";
    }

    public static void update3DWeather(DailyWeatherAdapter data) {
        //获取布局
        if (data != null) {
            RemoteViews   remoteViews   = new RemoteViews(context.getPackageName(), R.layout.widget_launcher_5);
            ComponentName componentName = new ComponentName(context, MAppWidget_5.class);
            //点击进入app
            remoteViews.setOnClickPendingIntent(R.id.wid_get_5_layout, getIntentToApp());
            AppWidgetManager                    appWidgetManager = AppWidgetManager.getInstance(context);
            List<DailyWeatherAdapter.DailyBean> daily            = data.getDaily();
            if (daily != null) {
                if (daily.size() >= 3) {
                    DailyWeatherAdapter.DailyBean today = daily.get(0);
                    //今天
                    remoteViews.setImageViewBitmap(R.id.widget5_icon, AppToolUtil.getweatherIcon(context, today.getIconDay()));
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append(today.getTextDay()).append(" ").append(today.getTempMax()).append("℃/").append(today.getTempMin()).append("℃");
                    remoteViews.setTextViewText(R.id.wdiget5_weather_info, stringBuilder);
                    //明天
                    DailyWeatherAdapter.DailyBean tomorrow = daily.get(1);
                    remoteViews.setImageViewBitmap(R.id.widget5_tmo_icon, AppToolUtil.getweatherIcon(context, tomorrow.getIconDay()));
                    remoteViews.setTextViewText(R.id.widget5_tom_weather, tomorrow.getTextDay());
                    remoteViews.setTextViewText(R.id.widget5_temp, tomorrow.getTempMax() + "℃/" + tomorrow.getTempMin() + "℃");
                    //后天
                    DailyWeatherAdapter.DailyBean after_tomorrow = daily.get(2);
                    remoteViews.setImageViewBitmap(R.id.widget5_atmo_icon, AppToolUtil.getweatherIcon(context, after_tomorrow.getIconDay()));
                    remoteViews.setTextViewText(R.id.widget5_atom_weather, after_tomorrow.getTextDay());
                    remoteViews.setTextViewText(R.id.widget5_atemp, after_tomorrow.getTempMax() + "℃/" + after_tomorrow.getTempMin() + "℃");
                }

                //更新
                appWidgetManager.updateAppWidget(componentName, remoteViews);
            }
        }
    }

    public static void getWeatherNow(Context context) {
        helper.getWeatherNow(sets.getDefaultCityCode(), new IAppWeatherHelper.NowWeatherResponse() {
            @Override
            public void success(WeatherNowAdapter data) {
                updateView(data);
            }

            @Override
            public void fail(String err) {
                Log.i(TAG, "获取现在：fail: "+err);
            }
        });
    }

    public static void getWeather3D(Context context) {
        helper.getDailyWeather(sets.getDefaultCityCode(), 3, new IAppWeatherHelper.DailyWeatherResponse() {
            @Override
            public void success(DailyWeatherAdapter data) {
                update3DWeather(data);
            }

            @Override
            public void fail(String err) {
                Log.i(TAG, "获取三天：fail: "+err);
            }
        });
    }

    /**
     * 和风天气未来7天数据被阉割
     * @param context
     */
    @Deprecated
    public static void getWeather7D(Context context) {
        helper.getDailyWeather(sets.getDefaultCityCode(), 7, new IAppWeatherHelper.DailyWeatherResponse() {
            @Override
            public void success(DailyWeatherAdapter data) {
                update7DWeather(data);
            }

            @Override
            public void fail(String err) {
                Log.i(TAG, "获取七天：fail: "+err);
            }
        });
    }


    public static void getData() {
        getWeather3D(context);
        getWeatherNow(context);
//        getWeather7D(context);
    }

}
